package com.pay;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;

//import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.app.PayTask;
import com.bean.WXPayBean;
import com.example.pay.R;
import com.kedll.library.contants.Consts;
import com.kedll.library.util.ToastUtil;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


public class PaySDKHelp {
    public static final int PAYCODE = 10101;
    private Activity mContext;
    private IWXAPI mWXApi;

    public PaySDKHelp(Activity context) {
        this.mContext = context;
        init();
    }


    private void init() {
        mWXApi = WXAPIFactory.createWXAPI(mContext, Consts.wxAppId);
    }

    /**
     * "url": "",
     * "wxobj": {
     * "nonceStr": "d6b900e1dcc945cda98e404cf0e1072b",
     * "package": "Sign=WXPay",
     * "partnerid": "1516418791",
     * "prepayid": "wx23103553009954866c8a690a4283301296",
     * "timeStamp": "1548210953",
     * "sign": "260C7D252B618575B0B6012EC72A2D3E"
     * }
     */
    public void pay(WXPayBean wxobj, String payType) {
        ToastUtil.showToast("正在进行支付");
        if ("weixin".equals(payType)) {
            weChatPay(wxobj);
        } else if ("alipay".equals(payType)) {
            aliPay(wxobj);
        }

    }


    private void weChatPay(WXPayBean wxobj) {
        PayReq req = new PayReq();
        req.appId = Consts.wxAppId;
        req.partnerId = wxobj.getWXOBJ().getPartnerid();
        req.prepayId = wxobj.getWXOBJ().getPrepayid();
        req.nonceStr = wxobj.getWXOBJ().getNonceStr();
        req.timeStamp = wxobj.getWXOBJ().getTimeStamp();
        req.packageValue = wxobj.getWXOBJ().getPackageValue();
        req.sign = wxobj.getWXOBJ().getSign();
        req.extData = "app data"; // optional
        mWXApi.sendReq(req);
    }

    @SuppressLint("CheckResult")
    private void aliPay(final WXPayBean wxobj) {
        Observable.create(new ObservableOnSubscribe<Map<String, String>>() {
            @Override
            public void subscribe(ObservableEmitter<Map<String, String>> e) throws Exception {
                PayTask alipay = new PayTask(mContext);
                //服务器获取订单Orderinfo
                Map<String, String> result = alipay.payV2(wxobj.getPaycmd(), true);
                Log.i("msp", result.toString());
                e.onNext(result);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Map<String, String>>() {

            @Override
            public void accept(Map<String, String> o) throws Exception {
                /**
                 * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                 */
                // 判断resultStatus 为9000则代表支付成功
                if (TextUtils.equals(o.get("resultStatus"), "9000")) {
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                    Log.i("支付成功", "需要依赖服务端的异步通知");
                } else {
                    // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    Log.i("支付失败", "需要依赖服务端的异步通知");
                }
            }
        });


//        Observable.create(new PayTask(mContext));

//        PayTask alipay = new PayTask(mContext);
//        //服务器获取订单Orderinfo
//        Map<String, String> result = alipay.payV2("Orderinfo", true);
//        Log.i("msp", result.toString());
//
//        Message msg = new Message();
//        msg.what = SDK_PAY_FLAG;
//        msg.obj = result;
//        mHandler.sendMessage(msg);
    }


    public void onDestroy() {
        mContext = null;
        mWXApi = null;
    }

}
